<?php

namespace app\admin\controller\org;

use app\admin\controller\Zlog;
use app\common\controller\Backend;
use fast\Tree;
use think\Db;
use think\Exception;

/**
 * 组织结构类别
 *
 * @icon fa fa-circle-o
 */
class Orgcate extends Backend
{
    
    /**
     * Orgcate模型对象
     * @var \app\admin\model\org\Orgcate
     */
    protected $model = null;
    protected $orgName_tree = [];
    protected $org_list = [];
    protected $current_info = [];
    protected $searchFields = 'name,mobile';
    protected $modelValidate = true;
    protected $modelSceneValidate = true;
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\org\Orgcate;
        $this->view->assign("statusList", $this->model->getStatusList());
        
        if(ORG_CATE_ID > 0){
            $org_where['parent_id|id'] = ORG_CATE_ID;
        }else{
            $org_where['level'] = array('in', array('1','2'));
        }
        $orgcateList = collection($this->model->where($org_where)->select())->toArray();
        $orgcat = [];
        $parent_ids = [];
        foreach($orgcateList as $k => $v){

            $orgcat[$v['id']] = $v['name'];
            $parent_ids[] = $v['id'];
        }
        $this->orgcat = $orgcat;
        $this->parent_ids = $parent_ids;
        Tree::instance()->init($orgcateList, 'parent_id');
        $this->org_list = $result = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0));
        $current = Db::name('org_cate')->where('id','=',ORG_CATE_ID)->find();
        $admin = Db::name('admin')->where('org_cate_id','=',ORG_CATE_ID)->order('id','asc')->limit(1)->select();
        $current['username'] = $admin[0]['username'];
        $current['avatar'] = $admin[0]['avatar'];
        $current['createtime'] = date('Y-m-s', $current['createtime']);
        $orgName_tree = [];
        foreach($result as $k => $v){
            $orgName_tree[$v['id']] = $v['name'];
        }
        $this->orgName_tree = $orgName_tree;
        $this->current_info = $current;
        $this->view->assign('org_cate_id', ORG_CATE_ID);
        $this->view->assign('current', $current);
        $this->view->assign('orgName_tree', $this->orgName_tree);
        $this->view->assign('orgcat', $this->orgcat);

    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    public function index(){

        if ($this->request->isAjax()) {
            if($this->request->request('keyField')){
                $data = $this->selectpage2();
                if(empty($data['list'])){
                    $data['list'] = array_merge([['id'=>0,'name'=>'总平台']], $data['list']);
                    $data['total'] = $data['total']+1;
                }
                return json($data);
            }
            if(ORG_CATE_ID > 0){
                $org_where['parent_id'] = ORG_CATE_ID;
                $ids1 = $this->model->where($org_where)->column('id');
                $ids2 = array();
                if($ids1){
                    $ids2 = $this->model->where('parent_id', 'in', $ids1)->column('id');
                }
                $ids = array_unique(array_merge($ids1, $ids2));
                $orgcateList = collection($this->model->where('id', 'in', $ids)->select())->toArray();
            }else{
                $org_where['level'] = array('in', array('1','2','3'));
                $orgcateList = collection($this->model->where($org_where)->select())->toArray();
            }
//            $orgcateList = collection($this->model->where($org_where)->select())->toArray();
            Tree::instance()->init($orgcateList, 'parent_id');
            $list = $result = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(ORG_CATE_ID));
            $total = count($this->org_list);
            $result = array("total" => $total, "rows" => $list, 'current'=>$this->current_info);
            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add($ids = null){

        $ids = $this->request->param('ids');
        $this->view->assign("ids", $ids);
        $this->relationSearch = false;
        if($this->request->isPost()){
            $params = $this->request->post("row/a", [], 'strip_tags');
            if($params){
                \think\Db::startTrans();
                try{
                    $validate = new \app\admin\validate\org\Orgcate;
                    if(!$validate->check($params)){
                        $this->error($validate->getError());//内置错误返回
                    }
                    if(isset($params['parent_id']) && $params['parent_id'] > 0){
                        $level = $this->model->where('id', $params['parent_id'])->value('level');
                        $params['level'] = $level+1;
                    }else{
                        $params['parent_id'] = ORG_CATE_ID;
                        $params['level'] = 2;
                    }
                    $params['createtime'] = time();
                    $org_id = $this->model->insertGetId($params);
                    if($org_id === false){
                        \think\Db::rollback();
                        $this->error($this->model->getError());
                    }
                    \think\Db::commit();

               } catch (Exception $e){
                    \think\Db::rollback();
                    $this->error($e->getMessage());
                }
                
                $this->success();    
            }
            $this->error();
            
        }   

        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row= $this->model->get(['id' => $ids]);
        
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a", [], 'strip_tags');
            if ($params) {
                $result = $row->save($params);
                if ($result === false) {
                    $this->error($row->getError());
                }
                $this->success();
            }
            $this->error();
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function grade($ids = null)
    {
        $row= $this->model->get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $group = Db::name('org_grade')->where('org_cate_id', $ids)->group('type')->column('type');
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a", [], 'strip_tags');
            $newgroup = $this->request->post("group/a", [], 'strip_tags');
            if ($params) {
                Db::startTrans();
                try{
                    $result = $row->save($params);
                    if ($result === false) {
                        $this->error($row->getError());
                    }
                    $data = array();
                    if(empty($newgroup)){
                        $delarr = $group;
                    }else{
                        $delarr = array_diff($group, $newgroup);
                    }
                    if(empty($group)){
                        $addarr = $newgroup;
                    }else{
                        $addarr = array_diff($newgroup, $group);
                    }
                    if($delarr){
                        Db::name('org_grade')->where('org_cate_id', $ids)->where('type', 'in', $delarr)->delete();
                    }
                    if($addarr){
                        $grd = [1=>[1,2,3],2=>[4,5,6,7,8,9],3=>[10,11,12], 4=>[13,14,15]];
                        foreach($addarr as $val){
                            if(isset($grd[$val]) && !empty($grd[$val])){
                                foreach($grd[$val] as $key=>$v){
                                    $data[$v]['type'] = $val;
                                    $data[$v]['group'] = $v;
                                    $data[$v]['org_cate_id'] = $ids;
                                    $data[$v]['create_time'] = time();
                                }
                            }
                        }
                    }
                    if($data){
                        $res = Db::name('org_grade')->insertAll($data);
                        if($res === false){
                            $this->error('属性保存失败！');
                        }
                    }
                    Db::commit();
                }catch (Exception $e){
                    Db::rollback();
                    $this->error($e->getMessage());
                }

                $this->success();
            }
            $this->error();
        }
        $arr = [
            1=>[
                'name'=>'幼儿',
                'checked'=>false
            ],
            2=>[
                'name'=>'小学',
                'checked'=>false
            ],
            3=>[
                'name'=>'初中',
                'checked'=>false
            ],
            4=>[
                'name'=>'高中',
                'checked'=>false
            ]];
        if($group){
            foreach($group as $val){
                $arr[$val]['checked'] = true;
            }
        }
        $this->view->assign("row", $row);
        $this->view->assign("group", $arr);
        return $this->view->fetch();
    }

    /**
     * 查看年纪班级
     */
    public function grade2($ids = null)
    {
        $row= $this->model->get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $group = $this->request->post("group/a", [], 'strip_tags');
            if($group){
                Db::startTrans();
                try{
                    $data = array();
                    $groupid = $group['group'];
                    Db::name('org_grade')->where('org_cate_id', $ids)->where('group', $groupid)->delete();
                    $number_str = isset($group['numbers'][$groupid])?$group['numbers'][$groupid]:'';
                    $number_str = str_replace('，',',', $number_str);
                    $number_arr = explode(',', $number_str);
                    if(!empty($number_arr)){
                        if(in_array($groupid,[1,2,3])){
                            $type = 1;
                        }elseif(in_array($groupid,[4,5,6,7,8,9])){
                            $type = 2;
                        }elseif(in_array($groupid,[10,11,12])){
                            $type = 3;
                        }else{
                            $type = 4;
                        }
                        foreach($number_arr as $key=>$val){
                            $data[$key]['type'] = $type;
                            $data[$key]['group'] = $groupid;
                            $data[$key]['org_cate_id'] = $ids;
                            $data[$key]['number'] = $val;
                            $data[$key]['create_time'] = time();
                        }
                    }
                    if($data){
                        $res = Db::name('org_grade')->insertAll($data);
                        if($res === false){
                            $this->error('班号保存失败！');
                        }
                    }
                    Db::commit();
                }catch (Exception $e){
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                $this->success();
            }
            $this->error();
        }
        $group = Db::name('org_grade')->where('org_cate_id', $ids)->order('group','asc')->select();
        $arr = [
            1=>'幼儿小班',
            2=>'幼儿中班',
            3=>'幼儿大班',
            4=>'一年级',
            5=>'二年级',
            6=>'三年级',
            7=>'四年级',
            8=>'五年级',
            9=>'六年级',
            10=>'初一年级',
            11=>'初二年级',
            12=>'初三年级',
            13=>'高一年级',
            14=>'高二年级',
            15=>'高三年级'];
        $groups = array();
        $current = 0;
        if($group){
            foreach($group as $k =>$val){
                if($k == 0){
                    $current = $val['group'];
                }
                $groups[$val['group']]['name'] = $arr[$val['group']];
                $groups[$val['group']]['number'][] = $val['number'];
            }
        }
        if($groups){
            foreach($groups as &$v){
                $v['numbers'] = implode(',', $v['number']);
            }
        }

        $this->view->assign("row", $row);
        $this->view->assign("groups", $groups);
        $this->view->assign("current", $current);
        return $this->view->fetch();
    }

    /*
     * 添加年纪班级
     */
    public function gradeadd()
    {
        $org_cate_id = $this->request->param('ids');
        $this->view->assign("ids", $org_cate_id);
        $this->model = new \app\admin\model\org\Orggrade;
        if ($this->request->isPost()) {
            $row = $this->request->post("row/a", [], 'strip_tags');
            if ($row) {
                $total = $this->model->where('number', '=', $row['number'])->where('org_cate_id', '=', $org_cate_id)->count();
                if($total > 0){
                    $this->error('该班号【'.$row['number'].'】已存在！');
                }
                if($org_cate_id > 0){
                    $row['org_cate_id'] = $org_cate_id;
                    $row['create_time'] = time();
                    $res = $this->model->insertGetId($row);
                    if($res === false){
                        $this->error($this->model->getError());
                    }
                    $this->success();
                }
                $this->error('单位编号错误！');
            }
            $this->error('缺少必要参数！');
        }
        return $this->view->fetch();
    }

    /*
     * 编辑年纪班级
     * @param null $ids
     * @return string
     */
    public function gradeedit($ids = null)
    {
        $this->model = new\app\admin\model\org\Orggrade;
        $row_data = $this->model->get(['id' => $ids]);
        if (!$row_data) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $row = $this->request->post("row/a", [], 'strip_tags');
            if ($row) {
                if($ids > 0){
                    $total = $this->model->where('number', '=', $row['number'])->where('id', '<>', $ids)->count();
                    if($total > 0){
                        $this->error('该班号【'.$row['number'].'】已存在！');
                    }
                    $result = $this->model->save($row,['id'=>$ids]);
                    if($result===false){
                        $this->error($this->model->getError());
                    }
                    $this->success();
                }
                $this->error('编号错误！');
            }
            $this->error('缺少必要参数！');
        }
        $this->view->assign("row", $row_data);
        return $this->view->fetch();
    }

    /*
     * 删除年纪班级
     * @param null $ids
     */
    public function gradedel($ids = null)
    {
        $this->model = new \app\admin\model\org\Orggrade;
        if ($ids) {
            $res = $this->model->where('id', 'in', $ids)->delete();
            if($res===false){
                $this->error($this->model->getError());
            }
            $this->success();
        }
        $this->error('编号错误！');
    }

    public function del($ids = null)
    {
        if ($ids) {
            $res = $this->model->where('id', 'in', $ids)->delete();
            if($res===false){
                $this->error($this->model->getError());
            }
            $res2 = $this->model->where('parent_id', 'in', $ids)->delete();
            if($res2===false){
                $this->error($this->model->getError());
            }
            $this->success();
        }
        $this->error('编号错误！');
    }

}
